import theano
import theano.tensor as T
import numpy as np
Theano
的随机数变量由 theano.sandbox.rng_mrg
中的 MRG_RandomStreams
实现(sandbox
表示是实验代码):
from theano.sandbox.rng_mrg import MRG_RandomStreams
新建一个 MRG_RandomStreams(seed=12345, use_cuda=None)
实例:
srng = MRG_RandomStreams()
它支持以下方法:
normal(size, avg=0.0, std=1.0, ndim=None, dtype=None, nstreams=None)
uniform(size, low=0.0, high=1.0, ndim=None, dtype=None, nstreams=None)
binomial(size=None, n=1, p=0.5, ndim=None, dtype='int64', nstreams=None)
multinomial(size=None, n=1, pvals=None, ndim=None, dtype='int64', nstreams=None)
与 np.random.random 不同,它产生的是随机数变量,而不是随机数数组,因此可以将 size
作为参数传给它:
rand_size = T.vector(dtype="int64")
rand_normal = srng.normal(rand_size.shape)
rand_uniform = srng.uniform(rand_size.shape)
rand_binomial = srng.binomial(rand_size.shape)
f_rand = theano.function(inputs = [rand_size],
outputs = [rand_normal, rand_uniform, rand_binomial])
print f_rand(range(5))[0]
print f_rand(range(5))[1]
print f_rand(range(5))[2]